import config from '@/config/index.js';
import dayjs from '@/js_sdk/dayjs/dayjs.min.js'
import api from '@/api/index.js'
import store from '@/store/index.js'
import XEUtils from '@/js_sdk/xe-utils/xe-utils.umd.min.js'

var Crypto = require('@/js_sdk/cryptojs/cryptojs.js').Crypto;

const utils = {

	hasPermission(permissionList, permission) {
		if (!permissionList || permissionList.length <= 0 || !permission || permission.length <= 0) {
			return false
		}
		let res = XEUtils.find(permissionList, item => item.toUpperCase() == permission.toUpperCase())
		return res != null
	},

	isUsername(username) {
		var reg = new RegExp('^[A-Za-z0-9\u4e00-\u9fa5]+$')
		return reg.test(username)
	},

	parseUsername(username) {
		var reg = /[^A-Za-z0-9\u4e00-\u9fa5]/g
		return username.replace(reg, '')
	},

	copyText(text) {
		uni.setClipboardData({
			data: text,
			showToast: false,
			success() {
				uni.showToast({
					icon: 'none',
					title: '复制成功'
				})
			},
			fail() {
				uni.showToast({
					icon: 'none',
					title: '复制失败'
				})
			}
		})
	},

	getMacAddressByScan() {
		return new Promise((resolve, reject) => {
			uni.scanCode({
				scanType: 'qrCode',
				success(res) {
					let content = res.result;

					if (utils.isMacAddress(content)) {
						resolve(content.replace(new RegExp(':', 'g'), ''));
					} else if (content.indexOf('http://www.ejiakanghu.com.cn/device/') == 0 ||
						content.indexOf('https://qrc.ejiakanghu.cn/qrcode/device/') == 0) {
						//设备二维码
						let rst = content.split('/');
						let qrc = rst[rst.length - 1];
						utils.getMacAddressByQrc(qrc).then((mac) => {
							if (utils.isMacAddress(mac)) {
								resolve(mac.replace(new RegExp(':', 'g'), ''));
							} else {
								utils.showToast('无效的二维码');
								reject('无效的二维码');
							}
						}).catch((error) => {
							reject(error);
						});
					} else {
						utils.showToast('无效的二维码');
						reject('无效的二维码');
					}
				},
				fail(error) {
					reject('扫码失败');
				}
			});
		});
	},

	getMacAddressByQrc(qrc) {
		return new Promise((resolve, reject) => {
			utils.showLoading({
				title: '获取MAC地址中',
				mask: true
			})
			uni.request({
				url: 'https://www.ejiakanghu.cn/routing_inspection/equLog/getMac',
				data: {
					markCode: qrc
				},
				success(res) {
					if (res.statusCode != 200 || !res.data || !res.data.macId) {
						console.log("获取MAC地址失败：" + res.data.message + '（' + res.statusCode + '）');
						uni.showModal({
							showCancel: false,
							content: '获取MAC地址失败，请联系系统管理员！' + res.data.message + '（' + res
								.statusCode + '）',
						});
						reject("获取MAC地址失败：" + res.data.message + '（' + res.statusCode + '）');
						return;
					}
					resolve(res.data.macId);
				},
				fail(error) {
					console.log("获取MAC地址失败=", error);
					uni.showModal({
						showCancel: false,
						content: '获取MAC地址失败，' + JSON.stringify(error),
					});
					reject(error);
				},
				complete() {
					utils.hideLoading();
				}
			});
		});
	},

	getBleBoxInfoByScan() {
		return new Promise((resolve, reject) => {
			uni.scanCode({
				scanType: 'qrCode',
				success(res) {
					console.log('扫码结果：', res)
					let content = res.result;
					if (utils.isMacAddress(content)) {
						// 设备MAC地址小二维码
						let hpMac = content.replace(new RegExp(':', 'g'), '').toUpperCase()
						api.getBleBoxInfo({
							hpMac: hpMac,
						}).then((res1) => {
							if (res1 && res1.data) {
								resolve(res1.data);
							} else {
								reject('获取设备信息失败，服务器未返回设备信息！');
							}
						}).catch(error => {
							reject(error);
						})
					} else if (content.indexOf('http://www.ejiakanghu.com.cn/device/') == 0 ||
						content.indexOf('https://qrc.ejiakanghu.cn/qrcode/device/') == 0) {
						let hpQrcode = content.replace(new RegExp(
								'http://www.ejiakanghu.com.cn/device/', 'g'),
							'https://qrc.ejiakanghu.cn/qrcode/device/')
						api.getBleBoxInfo({
							qrcode: hpQrcode,
							hpQrcode: hpQrcode,
						}).then(res1 => {
							if (res1 && res1.data) {
								resolve(res1.data);
							} else {
								reject('获取设备信息失败，服务器未返回设备信息！');
							}
						}).catch(error => {
							reject(error);
						})
					} else if (content.indexOf('https://qrc.ejiakanghu.cn/qrcode/equ/') == 0) {
						let equQrcode = content
						api.getBleBoxInfo({
							equQrcode: equQrcode,
						}).then(res1 => {
							if (res1 && res1.data) {
								resolve(res1.data);
							} else {
								reject('获取设备信息失败，服务器未返回设备信息！');
							}
						}).catch(error => {
							reject(error);
						})
					} else {
						reject('二维码扫描异常，请扫描围老归位桩二维码哦！');
					}
				},
				fail(error) {
					console.log(error)
					if (error && error.errMsg == 'scanCode:fail') {
						reject('二维码扫描异常，请扫描围老归位桩二维码哦！');
					} else if (error && error.errMsg == 'scanCode:fail cancel') {
						reject('二维码扫描异常，您主动取消了扫一扫！');
					} else {
						reject('二维码扫描异常，打开扫一扫失败，请检查微信是否有权限开启相机！');
					}
				}
			});
		});
	},

	/**
	 * 判断是否是MAC地址（包含或不包含冒号的MAC地址都是合法的MAC地址)
	 * @param {String} str
	 */
	isMacAddress(str) {
		var exp1 = /^([a-fA-F0-9]{2}:){5}([a-fA-F0-9]{2})$/
		var exp2 = /^([a-fA-F0-9]{2}){5}([a-fA-F0-9]{2})$/
		if (str.match(exp1) == null && str.match(exp2) == null) {
			return false
		}
		return true
	},

	parseDatetime(datetime, format) {
		return dayjs(datetime, 'YYYY-MM-DD HH:mm:ss').format(format)
	},

	parseAge(date, format) {
		let now = dayjs()
		let birthday = dayjs(date, format)
		let year = now.diff(birthday, 'year')
		if (year > 0) {
			return `${year}岁`
		}
		let month = now.diff(birthday, 'month')
		if (month > 0) {
			return `幼儿${month}个月`
		}
		let week = now.diff(birthday, 'week')
		if (week > 0) {
			return `幼儿${week}周`
		}
		let day = now.diff(birthday, 'day')
		if (day > 0) {
			return `幼儿${day}天`
		}
		return `新生儿`
	},

	guid() {
		return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
			var r = Math.random() * 16 | 0,
				v = c == 'x' ? r : (r & 0x3 | 0x8)
			return v.toString(16)
		})
	},

	// 格式化商品评价数量
	formatCommentSize(count) {
		if (count < 10) {
			return `${count}`
		} else if (count >= 10 && count <= 9999) {
			return `${parseInt(count / 10) * 10}+`
		} else {
			return `9999+`
		}
	},

	/**
	 * 选择城市，注意：仅支持微信小程序，且引入了腾讯位置服务城市选择插件
	 */
	citySelector() {
		const key = '4HLBZ-A2MH6-LQNSS-E6V2Z-PJ3ZK-IIBAL'; // 使用在腾讯位置服务申请的key
		const referer = '围老'; // 调用插件的app的名称
		const hotCitys = '苏州,广州'; // 用户自定义的的热门城市
		return new Promise((reslove, reject) => {
			uni.navigateTo({
				url: `plugin://citySelector/index?key=${key}&referer=${referer}&hotCitys=${hotCitys}`,
				success(res) {
					console.log(res)
					reslove(res)
				},
				fail(error) {
					console.log(error)
					reject(error)
				}
			})
		})
	},

	distanceText(lo1, la1, lo2, la2) {
		try {
			if (!lo1 || !la1 || !lo2 || !la2) {
				return false
			}
			let _distance = Number(utils.amapDistance(parseFloat(lo1), parseFloat(la1), parseFloat(lo2), parseFloat(
				la2)))
			return _distance > 1000 ? Number(_distance / 1000).toFixed(2) + 'km' : Number(_distance).toFixed(0) +
				'm'
		} catch (e) {
			return false
		}
	},

	/*作用: 由经纬度计算两点之间的直线距离 (可参考: 球面两点之间最短距离的计算方式)
	 * 参数1: 第一个坐标点的纬度(latitude的缩写, 一般在0~90之间)
	 * 参数2: 第一个坐标点的经度(longitude的缩写,一般在0~180之间)
	 * 参数3: 第二个坐标点的纬度
	 * 参数4: 第二个坐标点的经度
	 * 返回值: 返回距离(单位千米或公里)
	 */
	distance(la1, lo1, la2, lo2, fixed) {
		var La1 = (la1 * Math.PI) / 180.0;
		var La2 = (la2 * Math.PI) / 180.0;
		var La3 = La1 - La2;
		var Lb3 = (lo1 * Math.PI) / 180.0 - (lo2 * Math.PI) / 180.0;
		var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2), 2) + Math.cos(La1) * Math.cos(La2) * Math.pow(
			Math.sin(Lb3 / 2), 2)));
		s = s * 6378.137;
		s = Math.round(s * 10000) / 10000;
		s = s.toFixed((fixed != undefined ? fixed : 2));
		return Number(s);
	},

	amapDistance(lon1, lat1, lon2, lat2) {
		var radLat1 = (lat1 * Math.PI) / 180; //将角度换算为弧度
		var radLat2 = (lat2 * Math.PI) / 180; //将角度换算为弧度
		var a = radLat1 - radLat2;
		var b = (lon1 * Math.PI) / 180 - (lon2 * Math.PI) / 180;
		var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math
			.pow(
				Math.sin(b / 2), 2)));
		s = s * 6378137.0; // 取WGS84标准参考椭球中的地球长半径(单位:m)
		return Math.round(s); //(单位:m)
	},

	/**
	 * 清除所有缓存
	 */
	clearStorageSync() {
		let _storageKeys = utils.getStorageSync('STORAGE_CACHE_KEYS', false)
		if (_storageKeys && _storageKeys.length > 0) {
			_storageKeys.forEach(key => {
				if (key != 'STORAGE_CACHE_KEYS') {
					uni.removeStorageSync(key)
				}
			})
		}
	},

	/**
	 * 保存缓存数据（AES加密）
	 * @param {String} key
	 * @param {Object} data
	 */
	setStorageSync(key, data) {
		let _storageKeys = utils.getStorageSync('STORAGE_CACHE_KEYS', false)
		if (!_storageKeys || _storageKeys.length <= 0) {
			_storageKeys = []
		}
		if (_storageKeys.indexOf(key) == -1) {
			_storageKeys.push(key)
		}
		uni.setStorageSync('STORAGE_CACHE_KEYS', Crypto.AES.encrypt(JSON.stringify({
			key: 'STORAGE_CACHE_KEYS',
			data: _storageKeys
		}), config.AES_KEY).toString());
		uni.setStorageSync(key, Crypto.AES.encrypt(JSON.stringify({
			key: key,
			data: data
		}), config.AES_KEY).toString());
	},

	/**
	 * 读取缓存数据（AES加密）
	 * @param {String} key
	 * @param {Boolean} isRemove
	 */
	getStorageSync(key, isRemove) {
		try {
			let encryptStr = uni.getStorageSync(key);
			if (!utils.isEmpty(encryptStr)) {
				let bytes = Crypto.AES.decrypt(encryptStr, config.AES_KEY);
				let originalText = bytes.toString();
				let obj = JSON.parse(originalText)
				if (obj && obj.key && obj.key.length > 0) {
					if (isRemove) {
						uni.removeStorageSync(key)
					}
					return obj.data
				}
				uni.removeStorageSync(key)
				return null;
			}
			uni.removeStorageSync(key)
			return null;
		} catch (ex) {
			uni.removeStorageSync(key)
			return null;
		}
	},

	removeStorageSync(key) {
		uni.removeStorageSync(key)
	},

	/**
	 * 显示loading对话框
	 * @param {String} message
	 */
	showLoading(message) {
		try {
			uni.showLoading({
				title: message ? message : '数据加载中'
			});
		} catch (e) {}
	},

	/**
	 * 关闭loading对话框
	 */
	hideLoading() {
		try {
			uni.hideLoading();
		} catch (e) {}
	},

	/**
	 * 显示toast提示
	 * @param {String} title
	 * @param {Number} duration
	 */
	showToast(title, duration) {
		// #ifdef MP-WEIXIN
		uni.showToast({
			icon: 'none',
			title: title,
			duration: duration ? duration : 3000
		})
		// #endif
		// #ifdef MP-ALIPAY
		uni.showToast({
			icon: 'none',
			title: title,
		})
		// #endif
	},

	/**
	 * 打开页面，如果页面打开失败（页面打开层级超过10层限制)，则改用重定向
	 * @param {String} url
	 */
	openPage(url) {
		return new Promise((reslove, reject) => {
			uni.navigateTo({
				url: url,
				success(res) {
					console.log(res)
					reslove(res)
				},
				fail(error) {
					console.log(error)
					uni.redirectTo({
						url: url,
						success(res) {
							reslove(res)
						}
					});
				}
			});
		})
	},

	/**
	 * 判断是否为空
	 */
	isEmpty(s) {
		if (typeof s === 'undefined' || s === null || s === '') {
			return true;
		} else {
			return false;
		}
	},

	/**
	 * 手机号码
	 * @param {*} s
	 */
	isMobile(value) {
		//是否为手机号
		return /^(?:13\d|14\d|15\d|16\d|17\d|18\d|19\d)\d{5}(\d{3}|\*{3})$/.test(value);
	},

	/**
	 * 邮箱
	 * @param {*} s
	 */
	isEmail(s) {
		return /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(s);
	},

	/**
	 * 电话号码
	 * @param {*} s
	 */
	isPhone(s) {
		return /^0\d{2,3}-?\d{7,8}$/.test(s);
	},


	/**
	 * URL地址
	 * @param {*} s
	 */
	isURL(s) {
		return /^http[s]?:\/\/.*/.test(s);
	},

	//是否为空
	isNullOrEmpty(value) {

		return (value === null || value === '' || value === undefined) ? true : false;
	},

	//去空格
	trim(value) {
		return value.replace(/(^\s*)|(\s*$)/g, "");
	},

	//生成指定位数的随机数
	randomNumber(n) {
		if (n > 21) return null
		return parseInt((Math.random() + 1) * Math.pow(10, n - 1))
	},

	//获取客户端当前时间10位秒数UNIX时间戳
	timestamp() {
		return parseInt(new Date().getTime() / 1000);
	},

	//获取客户端当前时间13位秒数UNIX时间戳
	timestamp13() {
		return parseInt(new Date().getTime());
	},

	//获取URL地址中的GET参数
	getQuery(url, variable) {
		url = decodeURIComponent(url)
		var query = url.split("?")[1];
		var vars = query.split("&");
		for (var i = 0; i < vars.length; i++) {
			var pair = vars[i].split("=");
			if (pair[0] == variable) {
				return pair[1];
			}
		}
		return null;
	},

	//金额，只允许保留两位小数
	isMoneyFloat(value) {
		return /^(([1-9]\d*)|0)(\.\d{1,2})?$/.test(value);
	},

	//是否全为数字
	isNumber(value) {
		return /^[0-9]+$/.test(value);
	},

	//密码为8~20位数字和字母组合
	checkPwd(value) {
		return /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/.test(value);
	},

	//格式化距离，单位米
	formatDistance(distance) {
		if (distance < 1000) {
			return distance + 'm';
		} else {
			return Math.round((distance / 1000) * 100) / 100 + 'km';
		}
	},

	// 给价格后缀自动加上反斜杠
	formartSuffix(suffix) {
		if (!suffix) {
			return suffix
		}
		if (suffix.indexOf('/') == 0) {
			return suffix
		} else {
			return '/' + suffix
		}
	},

	//格式化手机号码
	formatMobile(num) {
		if (utils.isMobile(num)) {
			num = num.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
		}
		return num;
	},

	//金额格式化
	formatPrice(price) {
		let result = parseFloat(price).toFixed(2).toString().split('').reverse().join('').replace(/(\d{3})/g, '$1')
			.replace(
				/\,$/, '').split('').reverse().join('');
		return result
	},

	//日期格式化
	formatDate(formatStr, fdate) {
		if (fdate) {
			if (~fdate.indexOf('.')) {
				fdate = fdate.substring(0, fdate.indexOf('.'));
			}
			fdate = fdate.toString().replace('T', ' ').replace(/\-/g, '/');
			var fTime, fStr = 'ymdhis';
			if (!formatStr)
				formatStr = "y-m-d h:i:s";
			if (fdate)
				fTime = new Date(fdate);
			else
				fTime = new Date();
			var month = fTime.getMonth() + 1;
			var day = fTime.getDate();
			var hours = fTime.getHours();
			var minu = fTime.getMinutes();
			var second = fTime.getSeconds();
			month = month < 10 ? '0' + month : month;
			day = day < 10 ? '0' + day : day;
			hours = hours < 10 ? ('0' + hours) : hours;
			minu = minu < 10 ? '0' + minu : minu;
			second = second < 10 ? '0' + second : second;
			var formatArr = [
				fTime.getFullYear().toString(),
				month.toString(),
				day.toString(),
				hours.toString(),
				minu.toString(),
				second.toString()
			]
			for (var i = 0; i < formatArr.length; i++) {
				formatStr = formatStr.replace(fStr.charAt(i), formatArr[i]);
			}
			return formatStr;
		} else {
			return "";
		}
	},

	// GMT时间转普通时间
	gmtToDatetimeStr(time, format) {
		return new Date(time).Format(format);
	},

	// 获取定位位置
	getLocation(showOpenLocationModal) {
		let flag = true;
		if (showOpenLocationModal == false) {
			flag = false;
		}
		return new Promise((reslove, reject) => {
			uni.getLocation({
				success: function(res) {
					console.log(res);
					store.commit('cache/saveLastGps', res)
					reslove(res);
				},
				fail: function(res) {
					console.log(res);
					// #ifdef MP-ALIPAY
					if (res.errMsg == 'getLocation:fail 用户不允许授权') {
						if (flag) {
							uni.showModal({
								title: '系统提示',
								content: '请设置允许小程序访问位置信息',
								confirmText: '设置',
								cancelText: '取消',
								success: function(res) {
									if (res.confirm) {
										uni.openSetting();
									}
								}
							});
							reject('请设置允许小程序访问位置信息');
						} else {
							reject(res);
						}
						return;
					}
					// #endif

					if (res.errMsg == 'getLocation:fail auth deny') {
						if (flag) {
							uni.showModal({
								title: '系统提示',
								content: '请设置允许小程序访问位置信息',
								confirmText: '设置',
								cancelText: '取消',
								success: function(res) {
									if (res.confirm) {
										uni.openSetting();
									}
								}
							});
							reject('请设置允许小程序访问位置信息');
						} else {
							reject(res);
						}
						return;
					} else if (res.errMsg.indexOf('频繁调用') != -1) {
						reject('频繁调用')
						return;
					}

					if (flag) {
						utils.showOpenLocationModal().catch(error => {
							reject(error);
						});
					} else {
						reject('获取您的定位位置信息失败');
					}
				}
			});
		});
	},

	// 选择地图位置
	chooseLocation(showOpenLocationModal) {
		let flag = true;
		if (showOpenLocationModal == false) {
			flag = false;
		}
		return new Promise((reslove, reject) => {
			uni.chooseLocation({
				success: function(res) {
					console.log(res);
					reslove(res);
				},
				fail: function(res) {
					console.log(res);
					if (flag) {
						utils.showOpenLocationModal().catch(error => {
							reject(error);
						});
					} else {
						reject('获取您的定位位置信息失败');
					}
				}
			});
		});
	},

	// 显示未开启GPS或未设置允许小程序访问位置信息的对话框
	showOpenLocationModal() {
		return new Promise((reslove, reject) => {
			uni.getSetting({
				success(res) {
					if (res.authSetting.length <= 0 || res.authSetting['scope.userLocation'] ==
						false) {
						uni.showModal({
							title: '系统提示',
							content: '请设置允许小程序访问位置信息',
							confirmText: '设置',
							cancelText: '取消',
							success: function(res) {
								if (res.confirm) {
									uni.openSetting();
								}
							}
						});
						reject('请设置允许小程序访问位置信息');
					} else {
						reject('获取您的定位位置信息失败');
					}
				},
				fail(error) {
					console.log(error);
					uni.showModal({
						title: '系统提示',
						content: '获取位置信息失败，请检查手机GPS定位是否已打开',
						showCancel: false,
						success: function(res) {}
					});
					reject('获取位置信息失败，请检查手机GPS定位是否已打开');
				}
			});
		});
	},

	// 检查是否有蓝牙访问权限
	checkBluetoothAuth() {
		return new Promise((reslove, reject) => {
			// #ifdef MP-WEIXIN

			uni.getSetting({
				success(res) {
					console.log(res)
					if (res.authSetting && res.authSetting[
							'scope.bluetooth'] ==
						true) {
						reslove(res)
					} else {
						if (res.authSetting['scope.bluetooth'] == undefined) {
							reslove('低版本微信不支持蓝牙权限判断！')
							return
						}
						uni.showModal({
							title: '系统提示',
							content: '请设置小程序允许访问蓝牙',
							confirmText: '设置',
							cancelText: '取消',
							success: function(res) {
								if (res.confirm) {
									uni.openSetting();
								}
							}
						});
						reject('请设置小程序允许访问蓝牙');
					}
				},
				fail(error) {
					console.log(error);
					uni.showModal({
						title: '系统提示',
						content: '请设置小程序允许访问蓝牙',
						confirmText: '设置',
						cancelText: '取消',
						success: function(res) {
							if (res.confirm) {
								uni.openSetting();
							}
						}
					});
					reject('请设置小程序允许访问蓝牙');
				}
			});

			// #endif

			// #ifdef MP-ALIPAY

			if (my.canIUse('showAuthGuide.object.authType.BLUETOOTH')) {
				my.showAuthGuide({
					authType: 'BLUETOOTH',
					success: (res) => {
						if (res.shown) {
							console.log('显示弹窗，未获得蓝牙权限')
							reject(res)
						} else {
							console.log('不显示弹窗，已获得蓝牙权限')
							reslove(res)
						}
					},
					fail: (error) => {
						reject(error)
					},
				})
			} else {
				console.log('低版本不支持判断蓝牙权限')
				reslove('低版本不支持判断蓝牙权限')
			}

			// #endif
		});
	},

	// 打开webview网页
	openWebview(url, title) {
		if (title && title.length > 0) {
			uni.navigateTo({
				url: '/pkgWebView/pages/index/index?title=' + encodeURIComponent(title) + '&url=' +
					encodeURIComponent(url),
				fail(error) {
					uni.redirectTo({
						url: '/pkgWebView/pages/index/index?title=' + encodeURIComponent(title) +
							'&url=' +
							encodeURIComponent(url)
					});
				}
			});
		} else {
			uni.navigateTo({
				url: '/pkgWebView/pages/index/index?url=' + encodeURIComponent(url),
				fail(error) {
					uni.redirectTo({
						url: '/pkgWebView/pages/index/index?url=' + encodeURIComponent(url)
					});
				}
			});
		}
	},

	// 判断是否已登录，navigate默认true。navigate = true时，未登录则打开登录页面。navigate = false，未登录不跳转。
	isLogined(navigate) {
		let flag = true;
		if (navigate != undefined && navigate == false) {
			flag = false;
		}
		// #ifdef MP-WEIXIN
		if (utils.getStorageSync(`${__wxConfig.envVersion}-UINFO`)) {
			return true;
		} else {
			if (flag) {
				uni.navigateTo({
					url: '/pkgLogin/pages/index/index'
				});
			}
			return false;
		}
		// #endif
		// #ifdef MP-ALIPAY
		if (utils.getStorageSync(`ALIPAY-UINFO`)) {
			return true;
		} else {
			if (flag) {
				uni.navigateTo({
					url: '/pkgLogin/pages/index/index'
				});
			}
			return false;
		}
		// #endif
	},

	// 检查网络是否已连接
	isNetworkConnected(showModal) {
		let flag = false;
		if (showModal == true) {
			flag = true;
		}
		return new Promise((reslove, reject) => {
			// 获取网络类型
			uni.getNetworkType({
				success: (res) => {
					// #ifdef MP-WEIXIN
					if (res.networkType == 'none' || res.networkType == 'unknown') {
						if (flag) {
							uni.showModal({
								title: '系统提示',
								showCancel: false,
								content: '网络连接不可用，请检查网络设置'
							});
						}
						console.log('微信 http 检测网络，无网络', res)
						reject('网络连接不可用，请检查网络设置');
					} else {
						console.log('微信 http 检测网络，有网络', res)
						reslove(res);
					}
					// #endif

					// #ifdef MP-ALIPAY
					if (!res.networkAvailable) {
						if (flag) {
							uni.showModal({
								title: '系统提示',
								showCancel: false,
								content: '网络连接不可用，请检查网络设置'
							});
						}
						console.log('支付宝 http 检测网络，无网络', res)
						reject('网络连接不可用，请检查网络设置');
					} else {
						console.log('支付宝 http 检测网络，有网络', res)
						reslove(res);
					}
					// #endif
				},
				fail: (error) => {
					console.log('检测网络状态失败：', error);
					if (flag) {
						uni.showModal({
							title: '系统提示',
							showCancel: false,
							content: '网络连接不可用，请检查网络设置'
						});
					}
					reject('网络连接不可用，请检查网络设置');
				}
			});
		});
	},

	// 获取支付宝用户信息
	getAlipayUserInfo() {
		return new Promise((reslove, reject) => {
			if (my.getOpenUserInfo) {
				my.getOpenUserInfo({
					fail: (res) => {
						console.log(res);
					},
					success: (res) => {
						console.log(res);
						let resp = JSON.parse(res.response).response;
						if ((resp.nickName != undefined && resp.nickName.length > 0) ||
							parseInt(resp.code) == 10000) {
							if (resp.nickName == undefined || resp.nickName.length <= 0) {
								resp.nickName = '未设置昵称';
							}
							if (resp.avatar == undefined || resp.avatar.length <= 0) {
								resp.avatar = '';
							}
							reslove(resp);
						} else {
							reject(resp.msg + ',' + resp.subCode + ',' + resp.subMsg);
						}
					}
				});
			}
		});
	},

	// 获取微信登录授权code
	getWechatLoginOAuthCode() {
		return new Promise((reslove, reject) => {
			uni.login({
				provider: 'weixin',
				success(res) {
					console.log(res);
					if (!res.code) {
						reject('登录失败,错误信息: ' + res.errMsg);
					} else {
						reslove(res);
					}
				},
				fail(res) {
					console.log(res);
					reject('登录失败,错误信息: ' + JSON.stringify(res));
				}
			});
		});
	},

	// 获取支付宝登录授权code
	getAlipayLoginOAuthCode(scopes) {
		return new Promise((reslove, reject) => {
			uni.login({
				provider: 'alipay',
				scopes: scopes ? scopes : 'auth_base',
				success(res) {
					console.log(res);
					if (!res.code) {
						reject('登录失败,错误信息: ' + res.errMsg);
					} else {
						reslove(res);
					}
				},
				fail(res) {
					console.log(res);
					reject('登录失败,错误信息: ' + JSON.stringify(res));
				}
			});
		});
	},

	//字符串部分字符隐藏，显示为*
	plusXing(str, frontLen, endLen) {
		var len = str.length - frontLen - endLen;
		var xing = '';
		for (var i = 0; i < len; i++) {
			xing += '*';
		}
		return str.substring(0, frontLen) + xing + str.substring(str.length - endLen);
	},

	/**
	 * 获取view当前width值
	 * @param {This} vm
	 * @param {String} element
	 */
	getViewWidth(vm, element, vmLevel) {
		if (vmLevel == undefined) {
			vmLevel = 0;
		}
		for (var i = 0; i < vmLevel; i++) {
			vm = vm.$parent;
		}
		return new Promise((reslove, reject) => {
			let result = null;

			function run() {
				if (result != null) {
					return;
				}
				// #ifdef MP-ALIPAY
				my.createSelectorQuery()
					.select(element)
					.boundingClientRect()
					.exec(ret => {
						if (ret && Array.isArray(ret) && ret.length > 0 && ret[0] != undefined) {
							result = ret[0].width
						}
						if (result == null) {
							setTimeout(() => {
								run();
							}, 20);
						} else {
							reslove(result);
						}
					});
				// #endif
				// #ifdef MP-WEIXIN
				const query = uni.createSelectorQuery().in(vm);
				query
					.select(element)
					.boundingClientRect(data => {
						if (data) {
							result = data.width
						}
						if (result == null) {
							setTimeout(() => {
								run();
							}, 20);
						} else {
							reslove(result);
						}
					})
					.exec();
				// #endif
			}
			run();
		});
	},

	/**
	 * 获取view当前top+height的值
	 * @param {This} vm
	 * @param {String} element
	 */
	getViewTopHeight(vm, element, vmLevel) {
		if (vmLevel == undefined) {
			vmLevel = 0;
		}
		for (var i = 0; i < vmLevel; i++) {
			vm = vm.$parent;
		}
		return new Promise((reslove, reject) => {
			let result = null;

			function run() {
				if (result != null) {
					return;
				}
				// #ifdef MP-ALIPAY
				my.createSelectorQuery()
					.select(element)
					.boundingClientRect()
					.exec(ret => {
						if (ret && Array.isArray(ret) && ret.length > 0 && ret[0] != undefined) {
							result = ret[0].top + ret[0].height;
						}
						if (result == null) {
							setTimeout(() => {
								run();
							}, 20);
						} else {
							reslove(result);
						}
					});
				// #endif
				// #ifdef MP-WEIXIN
				const query = uni.createSelectorQuery().in(vm);
				query
					.select(element)
					.boundingClientRect(data => {
						if (data) {
							result = data.top + data.height;
						}
						if (result == null) {
							setTimeout(() => {
								run();
							}, 20);
						} else {
							reslove(result);
						}
					})
					.exec();
				// #endif
			}
			run();
		});
	},

	/**
	 * 获取view当前bottom+height的值
	 * @param {This} vm
	 * @param {String} element
	 */
	getViewBottomHeight(vm, element, vmLevel) {
		if (vmLevel == undefined) {
			vmLevel = 0;
		}
		for (var i = 0; i < vmLevel; i++) {
			vm = vm.$parent;
		}
		return new Promise((reslove, reject) => {
			let result = null;

			function run() {
				if (result != null) {
					return;
				}
				// #ifdef MP-ALIPAY
				my.createSelectorQuery()
					.select(element)
					.boundingClientRect()
					.exec(ret => {
						if (ret && Array.isArray(ret) && ret.length > 0 && ret[0] != undefined) {
							result = ret[0].bottom + ret[0].height;
						}
						if (result == null) {
							setTimeout(() => {
								run();
							}, 20);
						} else {
							reslove(result);
						}
					});
				// #endif
				// #ifdef MP-WEIXIN
				const query = uni.createSelectorQuery().in(vm);
				query
					.select(element)
					.boundingClientRect(data => {
						if (data) {
							result = data.bottom + data.height;
						}
						if (result == null) {
							setTimeout(() => {
								run();
							}, 20);
						} else {
							reslove(result);
						}
					})
					.exec();
				// #endif
			}
			run();
		});
	},

	/**
	 * 获取view当前bottom的值
	 * @param {This} vm
	 * @param {String} element
	 */
	getViewBottom(vm, element, vmLevel) {
		if (vmLevel == undefined) {
			vmLevel = 0;
		}
		for (var i = 0; i < vmLevel; i++) {
			vm = vm.$parent;
		}
		return new Promise((reslove, reject) => {
			let result = null;

			function run() {
				if (result != null) {
					return;
				}
				// #ifdef MP-ALIPAY
				my.createSelectorQuery()
					.select(element)
					.boundingClientRect()
					.exec(ret => {
						if (ret && Array.isArray(ret) && ret.length > 0 && ret[0] != undefined) {
							result = ret[0].bottom;
						}
						if (result == null) {
							setTimeout(() => {
								run();
							}, 20);
						} else {
							reslove(result);
						}
					});
				// #endif
				// #ifdef MP-WEIXIN
				const query = uni.createSelectorQuery().in(vm);
				query
					.select(element)
					.boundingClientRect(data => {
						if (data) {
							result = data.bottom;
						}
						if (result == null) {
							setTimeout(() => {
								run();
							}, 20);
						} else {
							reslove(result);
						}
					})
					.exec();
				// #endif
			}
			run();
		});
	},

	/**
	 * 获取view当前top的值
	 * @param {This} vm
	 * @param {String} element
	 */
	getViewTop(vm, element, vmLevel) {
		if (vmLevel == undefined) {
			vmLevel = 0;
		}
		for (var i = 0; i < vmLevel; i++) {
			vm = vm.$parent;
		}
		return new Promise((reslove, reject) => {
			let result = null;

			function run() {
				if (result != null) {
					return;
				}
				// #ifdef MP-ALIPAY
				my.createSelectorQuery()
					.select(element)
					.boundingClientRect()
					.exec(ret => {
						if (ret && Array.isArray(ret) && ret.length > 0 && ret[0] != undefined) {
							result = ret[0].top;
						}
						if (result == null) {
							setTimeout(() => {
								run();
							}, 20);
						} else {
							reslove(result);
						}
					});
				// #endif
				// #ifdef MP-WEIXIN
				const query = uni.createSelectorQuery().in(vm);
				query
					.select(element)
					.boundingClientRect(data => {
						if (data) {
							result = data.top;
						}
						if (result == null) {
							setTimeout(() => {
								run();
							}, 20);
						} else {
							reslove(result);
						}
					})
					.exec();
				// #endif
			}
			run();
		});
	},

	/**
	 * 获取view当前height的值
	 * @param {This} vm
	 * @param {String} element
	 */
	getViewHeight(vm, element, vmLevel) {
		if (vmLevel == undefined) {
			vmLevel = 0;
		}
		for (var i = 0; i < vmLevel; i++) {
			vm = vm.$parent;
		}
		return new Promise((reslove, reject) => {
			let result = null;

			function run() {
				if (result != null) {
					return;
				}
				// #ifdef MP-ALIPAY
				my.createSelectorQuery()
					.select(element)
					.boundingClientRect()
					.exec(ret => {
						if (ret && Array.isArray(ret) && ret.length > 0 && ret[0] != undefined) {
							result = ret[0].height;
						}
						if (result == null) {
							setTimeout(() => {
								run();
							}, 20);
						} else {
							// console.log(element, ret, result)
							reslove(result);
						}
					});
				// #endif
				// #ifdef MP-WEIXIN
				const query = uni.createSelectorQuery().in(vm);
				query
					.select(element)
					.boundingClientRect(data => {
						if (data) {
							result = data.height;
						}
						if (result == null) {
							setTimeout(() => {
								run();
							}, 20);
						} else {
							reslove(result);
						}
					})
					.exec();
				// #endif
			}
			run();
		});
	},

	/**
	 * 获取view当前Rect的值
	 * @param {This} vm
	 * @param {String} element
	 */
	getViewRect(vm, element, vmLevel) {
		if (vmLevel == undefined) {
			vmLevel = 0;
		}
		for (var i = 0; i < vmLevel; i++) {
			vm = vm.$parent;
		}
		return new Promise((reslove, reject) => {
			let result = null;

			function run() {
				if (result != null) {
					return;
				}
				// #ifdef MP-ALIPAY
				my.createSelectorQuery()
					.select(element)
					.boundingClientRect()
					.exec(ret => {
						if (ret && Array.isArray(ret) && ret.length > 0 && ret[0] != undefined) {
							result = ret[0];
						}
						if (result == null) {
							setTimeout(() => {
								run();
							}, 20);
						} else {
							// console.log(element, ret, result)
							reslove(result);
						}
					});
				// #endif
				// #ifdef MP-WEIXIN
				const query = uni.createSelectorQuery().in(vm);
				query
					.select(element)
					.boundingClientRect(data => {
						if (data) {
							result = data;
						}
						if (result == null) {
							setTimeout(() => {
								run();
							}, 20);
						} else {
							reslove(result);
						}
					})
					.exec();
				// #endif
			}
			run();
		});
	},

	imageFileToBase64(path) {
		const imgData = uni.getFileSystemManager().readFileSync(path, 'base64');
		if (path.lastIndexOf('.png') != -1 || path.lastIndexOf('.PNG') != -1) {
			return 'data:image/png;base64,' + imgData
		}
		return 'data:image/jpeg;base64,' + imgData
	},

}

Date.prototype.Format = function(fmt) { //author: meizz   
	var o = {
		"M+": this.getMonth() + 1, //月份   
		"d+": this.getDate(), //日   
		"h+": this.getHours(), //小时   
		"m+": this.getMinutes(), //分   
		"s+": this.getSeconds(), //秒   
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度   
		"S": this.getMilliseconds() //毫秒   
	};
	if (/(y+)/.test(fmt))
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o)
		if (new RegExp("(" + k + ")").test(fmt))
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k])
				.length)));
	return fmt;
};

export default utils